//
//  LGTabBar.swift
//  01-Weibo项目练习-1
//
//  Created by 李李刚 on 16/3/3.
//  Copyright © 2016年 李李刚. All rights reserved.
//

import UIKit

class LGTabBar: UITabBar {
    

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init?(coder )没有被执行")
    }
    
    func setupUI(){
        
        self.backgroundImage = UIImage(named: "tabbar_background")

        
       addSubview(centerButton)
        
        
    }
    
    
    //懒加载一个按钮
    private lazy var centerButton: UIButton = {
        let t = UIButton()
        //设置按钮图片
        t.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        t.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Selected)
        
        t.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        
        t.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Selected)
        
        //添加点击事件
        t.addTarget( self, action: "centerButtonDidClick", forControlEvents: .TouchUpInside)
        
        //自适应大小
        t.sizeToFit()
        
        return t
        
        
    }()
    
    func centerButtonDidClick(){
        
        print("中心按钮点击")
        
    }
    
    
    //重写layoutsubview方法给控件设置frame  ---重新设置tabbar上item的frame
    override func layoutSubviews() {
        
        centerButton.center = CGPointMake(self.bounds.width/2, self.bounds.height/2)
        
        print("------",subviews)
        
        //每个控件的宽度
        let itemW = self.bounds.width/5
        
        var idnex = 0;
        
        for value in self.subviews{
            
            if value.isKindOfClass( NSClassFromString("UITabBarButton")! ){
                
                //设置控件的frame
                let x = itemW * CGFloat(idnex)
                
                //赋值
                value.frame.origin.x = x
                value.bounds.size.width = itemW
                
                idnex++
                
                //跳过第三个centerButton
                if idnex == 2 {
                    
                    idnex++
                }
                
            }
            
            
            
            
            
        }
        
        
        
    }
    

}
